"""
  Created by Amor on 2018-08-12
"""
from django.db.models import Q
from rest_framework import serializers

from .models import Goods, GoodsCategory, GoodsImage, HotSearchWords, Banner, GoodsCategoryBrand, IndexAd

__author__ = '骆杨'


class CategorySerializer(serializers.ModelSerializer):

    class SubCategorySerializer(serializers.ModelSerializer):

        class SubCategorySerializer(serializers.ModelSerializer):

            class Meta:
                model = GoodsCategory
                fields = '__all__'

        class Meta:
            model = GoodsCategory
            fields = '__all__'

        sub_cat = SubCategorySerializer(many=True)

    class Meta:
        model = GoodsCategory
        fields = '__all__'

    sub_cat = SubCategorySerializer(many=True)


class GoodsImageSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsImage
        fields = ('image', )


class GoodsSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    images = GoodsImageSerializer(many=True)

    class Meta:
        model = Goods
        fields = '__all__'


class HotSearchSerializer(serializers.ModelSerializer):

    class Meta:
        model = HotSearchWords
        fields = '__all__'


class BannerSerializer(serializers.ModelSerializer):

    class Meta:
        model = Banner
        fields = '__all__'


class BrandSerializer(serializers.ModelSerializer):

    class Meta:
        model = GoodsCategoryBrand
        fields = '__all__'


class IndexGoodsSerializer(serializers.ModelSerializer):

    class SubCategorySerializer(serializers.ModelSerializer):
        class Meta:
            model = GoodsCategory
            fields = '__all__'

    brands = BrandSerializer(many=True)
    goods = serializers.SerializerMethodField()
    sub_cat = SubCategorySerializer(many=True)
    ad_goods = serializers.SerializerMethodField()

    def get_goods(self, obj):
        all_goods = Goods.objects.filter(Q(category_id=obj.id) |
                                         Q(category__parent_category_id=obj.id) |
                                         Q(category__parent_category__parent_category_id=obj.id))
        goods_serializer = GoodsSerializer(all_goods, many=True)
        return goods_serializer.data

    def get_ad_goods(self, obj):
        goods_json = {}
        ad_goods = IndexAd.objects.filter(category_id=obj.id)
        if ad_goods:
            good_ins = ad_goods[0].goods
            goods_json = GoodsSerializer(good_ins, many=False, context={'request': self.context['request']}).data
        return goods_json

    class Meta:
        model = GoodsCategory
        fields = '__all__'
